<template>
  <a class="fa-riding-button tools-btn" :class="{ 'is-active': isActive }" @click="openArea">
    骑缝章
    <i class="fa-riding-button__icon fa-icon-riding"></i>
  </a>
</template>

<script lang="ts">
import { computed, defineComponent, inject, nextTick, watch } from 'vue'
import { Viewer } from '@/types'
import { scrollTo } from '@/utils'

interface CSSStyle extends CSSStyleDeclaration {
  zoom: string
}

// 骑缝控件按钮
export default defineComponent({
  name: 'RidingButton',

  props: {
    /** 是否激活骑缝区域 */
    active: {
      type: Boolean,
      default: false
    }
  },

  setup(props, { emit }) {
    /** 文档查看器 */
    const viewer = inject('Viewer') as Viewer

    /** 滚动元素 */
    const scroller = computed(() => viewer.scroller)

    /** 是否激活骑缝区域 */
    const isActive = computed({
      set: val => emit('update:active', val),
      get: () => props.active
    })

    let scrollTimer = 0
    let startScrollTime: number

    /** 滚动到区域 */
    function scrollToArea(isStart = true) {
      const scr = scroller.value
      const now = +new Date()

      if (!scr) return

      clearTimeout(scrollTimer)

      const srcStyle = scr.style as CSSStyle

      // 开始执行时记录时间
      if (isStart) {
        // Fix: 解决 QQ 浏览器横向滚动条失效
        srcStyle.zoom = '1.00001'
        startScrollTime = now
      }

      // 动画结束后停止
      if (now - startScrollTime > 350) {
        srcStyle.zoom = '1'
        return
      }

      scrollTo(scr, scr.scrollWidth, undefined, false)

      // 递归执行动画
      scrollTimer = window.setTimeout(() => scrollToArea(false), 10)
    }

    // 文档切换
    watch(
      () => viewer.doc,
      async () => {
        await nextTick()
        // 有骑缝控件则自动展开
        if (viewer.docRidings.length) isActive.value = true
      },
      {
        immediate: true
      }
    )

    return {
      isActive,

      /** 开启骑缝区域 */
      openArea() {
        const willOpen = !isActive.value
        isActive.value = willOpen

        if (willOpen) scrollToArea()
      }
    }
  }
})
</script>

<style lang="scss">
.fa-riding-button {
  width: 32px;
  padding: 8px 8px;
  font-size: 12px;
  line-height: 16px;
  @extend .fa-btn-light;

  &__icon {
    display: inline-block;
    margin-top: 6px;
    font-size: 16px;
    line-height: 1;
  }
}
</style>
